<?php
class ExcelWrite {
    public static function creatFile($array) {
        $file = self::xlsBOF();
        $tr1 = 0;

        foreach($array as $k => $v) {
            $nn1 = 0;
            foreach($v as $k1 => $v1) {
                $file .= self::xlsWriteLabel($tr1, $nn1, $v1);
                $nn1 ++;
            }
            $tr1 ++;
        }

        $file .= self::xlsEOF();
        return $file;
    }

    public static function downloadFile($array, $filename) {
        header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");  
  header("Content-Type: application/force-download");
  header("Content-Type: application/octet-stream");
  header("Content-Type: application/download");
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
        header('Content-Disposition: attachment;filename=' . $filename);
        header('Content-Transfer-Encoding: binary ');
        echo self::CreatFile($array);
    }

    private static function xlsBOF() {
        return pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
    }

    static function xlsEOF() {
        return pack("ss", 0x0A, 0x00);
    }

    private static function xlsWriteNumber($Row, $Col, $Value) {
        return pack("sssss", 0x203, 14, $Row, $Col, 0x0) . pack("d", $Value);
    }

    static function xlsWriteLabel($Row, $Col, $Value) {
        $Value = iconv("UTF-8", "gbk", $Value); //加上本语句，解决导出excel文件乱码问题20110629
        $L = strlen($Value);
        return pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L) . $Value;
    }
}